<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>

    <script src="https://unpkg.com/vue"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vuetify@3.5.17/dist/vuetify.min.css" />
    <link href="https://cdn.jsdelivr.net/npm/@mdi/font@5.x/css/materialdesignicons.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/vuetify@3.5.17/dist/vuetify.min.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://unpkg.com/vee-validate"></script>

</head>

<body>
    <div id="app">
        <v-card flat>
            <v-card-title class="d-flex align-center pe-2">
                <v-text-field v-model="search" density="compact" label="搜索" prepend-inner-icon="mdi-magnify"
                    variant="solo-filled" flat hide-details single-line></v-text-field> <v-col cols="auto">
                    <v-btn density="compact" icon="mdi-plus" @click="dialog = true;"></v-btn>
                    <v-btn density="compact" icon="mdi-calendar" @click="shwoYourRandom"></v-btn>
                </v-col>
            </v-card-title>

            <v-divider></v-divider>
            <v-data-table v-model:search="search" :items="items" :headers="headers">
                <template v-slot:item.image="{ item }">
                    <v-card class="my-2" elevation="2" rounded>
                        <v-img :src="`${item.pictureFile}`" height="64" cover></v-img>
                    </v-card>
                </template>

                <template v-slot:item.actions="{ item }">
                    <v-icon class="me-2" size="small" @click="editItem(item,1)">
                        mdi-pencil
                    </v-icon>
                    <v-icon size="small" @click="deleteItem(item)">
                        mdi-delete
                    </v-icon>
                </template>

            </v-data-table>
        </v-card>
        <v-dialog v-model="dialog" max-width="500px" @update:model-value="dialogReset">
            <v-card>
                <v-card-title>
                    <span class="text-h5">{{editType == 0 ? '新增':"编辑"}}</span>
                </v-card-title>

                <v-card-text>
                    <v-container>
                        <form @submit.prevent="submit">
                            <v-text-field v-model="formData.name" :counter="10" :error-messages="输入正确的信息" label="英雄名称"
                                :error-messages="name.errorMessage.value"></v-text-field>
                            <v-text-field v-model="formData.courtesyTitle" :counter="10" :error-messages="输入正确的信息"
                                label="英雄尊称"></v-text-field>
                            <v-textarea v-model="formData.backgroundStory" :counter="10" :error-messages="输入正确的信息"
                                label="英雄事迹"></v-textarea>
                            <v-file-input prepend-icon="mdi-camera" accept="image/png, image/jpeg" show-size
                                :counter="10" label="英雄原画" @update:model-value="updated"></v-file-input>
                            <v-btn class="me-4" type="submit">
                                提交
                            </v-btn>
                            <v-btn @click="reset">
                                清空
                            </v-btn>
                        </form>
                    </v-container>
                </v-card-text>
            </v-card>
        </v-dialog>
        <v-dialog transition="dialog-bottom-transition" width="auto" v-model="YourRandomWindow">
            <template v-slot:activator="{ props: activatorProps }">
                <v-btn v-bind="activatorProps" text="Transition from Bottom" block></v-btn>
            </template>
            <template v-slot:default="{ isActive }">
                <v-card width="500px">
<!--                    <v-toolbar title="随机列表"></v-toolbar>-->
                    <v-card-text class="d-flex justify-center">
                        <div class="d-flex">
                            <v-list>
                                <div class="text-h4 ">红色方</div>
                                <v-list-item
                                        v-for="item in heroList1"
                                        :key="item.id"
                                        :title="item.courtesyTitle"
                                ></v-list-item>
                            </v-list>
                                <v-list>
                                    <div class="text-h4 ">蓝色方</div>
                                    <v-list-item
                                            v-for="item in heroList2"
                                            :key="item.id"
                                            :title="item.courtesyTitle"
                                    ></v-list-item>
                                </v-list>
                        </div>

                    </v-card-text>

                    <v-card-actions class="justify-end">
                        <v-btn text="关闭" @click="isActive.value = false"></v-btn>
                    </v-card-actions>
                </v-card>
            </template>
        </v-dialog>
    </div>

    <script>
        const { createApp, ref, reactive, toRefs, onMounted, watch } = Vue;
        const { createVuetify } = Vuetify;
        const { useField, useForm } = VeeValidate;
        const vue3Composition = {
            setup() {
                let search = ref('');
                let headers = reactive([
                    {
                        title: 'id',
                        key: 'id',
                    },
                    { title: '头像', key: 'image', width: '100px' },
                    { title: '名称', key: 'name' },
                    { title: '尊称', key: 'courtesyTitle' },
                    { title: '事迹', key: 'backgroundStory' },
                    { title: '原画', key: 'image', width: '150px' },
                    { title: '操作', key: 'actions', sortable: false },
                ]);
                let items = ref([]);
                let dialog = ref(false);
                const formData = ref({
                    name: "",
                    courtesyTitle: "",
                    backgroundStory: "",
                    pictureFile: "",
                });

                let reader = new FileReader();
                let files = ref();

                const { handleSubmit, handleReset } = useForm({
                    validationSchema: {
                        name(value) {
                            if (value?.length >= 2) return true

                            return 'Name needs to be at least 2 characters.'
                        }
                    },
                });

                let editType = ref(0);

                const name = useField('name');

                let YourRandomWindow = ref(false)
                let randomNumber = ref(15);
                let times = ref(2);
                let heroList1 = ref([]);
                let heroList2 = ref([]);
                onMounted(() => {
                    getdata();
                    shwoYourRandom();
                });

                // api getAllData
                function getdata() {
                    let url = 'http://localhost:8088/hero/list';
                    axios.get(url).then(res => {
                        items.value = res.data;
                    }).catch(function (error) {
                        // 处理错误情况
                        console.error(error);
                    })
                }

                // api add
                function add(data) {
                    let url = 'http://localhost:8088/hero/add';
                    axios.post(url, data).then(res => {
                        alert('添加成功！');
                        items.value = res.data;
                    }).catch(function (error) {
                        // 处理错误情况
                        console.error(error);
                    })
                }

                // api searchById
                function searchById(data) {
                    let url = `http://localhost:8088/hero/searchById/${data}`;
                    axios.get(url).then(res => {
                        items.value = res.data;
                    }).catch(function (error) {
                        // 处理错误情况
                        console.error(error);
                    })
                }

                // api updateById
                function updateById(data) {
                    let url = `http://localhost:8088/hero/updateById`;
                    axios.post(url, data).then(res => {
                        items.value = res.data;
                    }).catch(function (error) {
                        // 处理错误情况
                        console.error(error);
                    })
                }

                // api getAllData
                async function getRandomData(data) {
                    let url = `http://localhost:8088/hero/random/${data}`;
                    return await axios.get(url);
                }


                function updated(file) {
                    getBase64Image(file).then((res) => {
                        formData.value.pictureFile = `data:image/gif;base64,${res}`;
                    })

                };

                function getBase64Image(file) {
                    return new Promise((resolve, reject) => {
                        // 创建一个新的 FileReader 对象
                        const reader = new FileReader();
                        // 读取 File 对象
                        reader.readAsDataURL(file);
                        // 加载完成后
                        reader.onload = function () {
                            // 将读取的数据转换为 base64 编码的字符串
                            const base64String = reader.result.split(",")[1];
                            // 解析为 Promise 对象，并返回 base64 编码的字符串
                            resolve(base64String);
                        };

                        // 加载失败时
                        reader.onerror = function () {
                            reject(new Error("Failed to load file"));
                        };
                    });
                };

                function submit() {
                    // 表单验证暂时不做
                    if (editType == 0) {
                        add(formData.value);
                    } else {
                        updateById(formData.value);
                    }
                }


                function reset() {
                    formData.value = {
                        name: "",
                        courtesyTitle: "",
                        backgroundStory: "",
                        pictureFile: "",
                    };
                    editType.value = 0;
                }

                function editItem(item, type) {
                    formData.value = item;
                    dialog.value = true;
                    editType.value = type;
                }

                function dialogReset() {
                    if (dialog.value == 0) {
                        reset();
                    }
                }

                async function shwoYourRandom() {
                    YourRandomWindow.value = true;
                    // 总数量
                    let number = randomNumber.value * times.value;
                    let datas = await getRandomData(number);
                    let half = Math.ceil(datas.data.length / 2);
                    heroList1.value = (datas.data.splice(0, half));
                    console.log(heroList1.value)
                    heroList2.value = (datas.data.splice(-half));
                }
                return {
                    search,
                    items,
                    headers,
                    dialog,
                    formData,
                    files,
                    editType,
                    YourRandomWindow,
                    randomNumber,
                    times,
                    heroList1,
                    heroList2,
                    getdata,
                    reset,
                    submit,
                    updated,
                    editItem,
                    dialogReset,
                    shwoYourRandom,
                }
            }
        }

        const vuetify = createVuetify();
        const app = createApp(vue3Composition)
            .use(vuetify)
            .mount('#app');
    </script>
</body>

</script>
</html>